/**
 * unPlarer-Youtube 0.8.0 
 *
 * @author Alvaro Lopez, Juan Baquero
 * 
 * http://code.google.com/p/unplayer-youtube/
 **/

package unplayer.youtubeplayer.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import processing.core.PApplet;

public class StreamVideo extends Thread {
	
	public StreamVideo(UrlStream caller)
	{
		this.call = caller;
	}
	
	
	public void loadVideo(PApplet pa,String url,String file)
	{
		parent=pa;
		urlStream = url;
		this.file = file;
	}
	
	
	public void run()
	{
		URL newUrl = null;

		try
		{
			out = parent.createOutput(file);
			bufferedOutput = new BufferedOutputStream(out);

			
			newUrl = new URL(urlStream);
		    isReader = newUrl.openStream();
		    bufferedInput = new BufferedInputStream(isReader);


			byte [] array = new byte[30000];
			int leidos = bufferedInput.read(array);
			while (leidos > 0)
			{
				//PApplet.saveBytes(out, array);
				bufferedOutput.write(array,0,leidos);
				leidos=bufferedInput.read(array);
			}

			// Cierre de los ficheros
			bufferedInput.close();
			isReader.close();
			out.close();
			bufferedOutput.close();
		}
		catch (Exception e)
		{
			//e.printStackTrace();
			call.loadResults(UrlStream.NO_CONNECTION);
		}

	}

	public void close()
	{
		try {
			isReader.close();
			out.close();
			bufferedOutput.close();
			bufferedInput.close();
			
		} catch (IOException e) {
			//
		}
		
	}
	
	private String urlStream;
	private PApplet parent;
	private String file;
	private UrlStream call;
	
	private InputStream isReader = null;
	private BufferedInputStream bufferedInput = null;
	private BufferedOutputStream bufferedOutput;
	private OutputStream out;

}
